/*
 * Copyright (C) 2010 Michael Pardo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.activeharmony.sample.slice;

import com.activeharmony.sample.ResourceTable;
import com.activeharmony.sample.utils.LogUtil;

import com.activeharmony.Configuration;
import com.activeharmony.query.Delete;
import com.activeharmony.query.Select;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * MainAbilitySlice.
 */
public class MainAbilitySlice extends AbilitySlice {
    Holder holder = new Holder();

    Details detailsObj = new Details();

    List<Details> detailsList = new ArrayList<>();

    /**
     * onStart.
     *
     * @param intent intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_layout);
        initialization();
        addOnClickActionOne();
        addOnClickActionTwo();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void initialization() {
        Component component = findComponentById(ResourceTable.Id_id);
        if (component != null && component instanceof TextField) {
            holder.edtId = (TextField) component;
        }
        component = findComponentById(ResourceTable.Id_name);
        if (component != null && component instanceof TextField) {
            holder.edtName = (TextField) component;
        }
        component = findComponentById(ResourceTable.Id_age);
        if (component != null && component instanceof TextField) {
            holder.edtAge = (TextField) component;
        }
        component = findComponentById(ResourceTable.Id_insert);
        if (component != null && component instanceof Button) {
            holder.btnInsert = (Button) component;
        }
        component = findComponentById(ResourceTable.Id_read_all);
        if (component != null && component instanceof Button) {
            holder.btnReadAll = (Button) component;
        }
        component = findComponentById(ResourceTable.Id_read_one);
        if (component != null && component instanceof Button) {
            holder.btnReadOne = (Button) component;
        }
        component = findComponentById(ResourceTable.Id_delete_all);
        if (component != null && component instanceof Button) {
            holder.btnDeleteAll = (Button) component;
        }
        component = findComponentById(ResourceTable.Id_delete);
        if (component != null && component instanceof Button) {
            holder.btnDelete = (Button) component;
        }
        component = findComponentById(ResourceTable.Id_update);
        if (component != null && component instanceof Button) {
            holder.btnUpdate = (Button) component;
        }
    }

    private void addOnClickActionOne() {
        holder.btnInsert.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isEmpty(holder.edtName) && isEmpty(holder.edtAge)) {
                    detailsObj.setName(holder.edtName.getText().trim());
                    detailsObj.setAge(holder.edtAge.getText().trim());
                    insertData(detailsObj);
                } else {
                    showToast("Enter in All Fields");
                }
            }
        });

        holder.btnReadAll.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                detailsList = getAll();
                populate(detailsList);
            }
        });

        holder.btnReadOne.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                detailsList.clear();
                if (isEmpty(holder.edtId)) {
                    Details details = getOne(holder.edtId.getText().trim());
                    populate(details);
                } else {
                    showToast("Enter Id to read");
                }
            }
        });

        holder.btnDeleteAll.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                deleteAll();
            }
        });
    }

    private void addOnClickActionTwo() {
        holder.btnDelete.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (isEmpty(holder.edtId)) {
                    deleteOne(Long.parseLong(holder.edtId.getText().trim()));
                } else {
                    showToast("Enter Id to Delete");
                }
            }
        });

        holder.btnUpdate.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                detailsList.clear();
                if (isEmpty(holder.edtId) && isEmpty(holder.edtName)
                        && isEmpty(holder.edtAge)) {
                    Details details = getOne(holder.edtId.getText().trim());
                    details.setName(holder.edtName.getText().trim());
                    details.setAge(holder.edtAge.getText().trim());
                    updateData(details);
                } else {
                    showToast("Enter in All Fields");
                }
            }
        });
    }

    private void showToast(String message) {
        ToastDialog loginToast = new ToastDialog(getApplicationContext());
        loginToast.setText(message).show();
    }

    /**
     * Holder Class for UI elemnts.
     */
    static class Holder {
        TextField edtName;

        TextField edtAge;

        TextField edtId;

        Button btnInsert;

        Button btnReadAll;

        Button btnReadOne;

        Button btnDeleteAll;

        Button btnDelete;

        Button btnUpdate;
    }

    // validating Text Field Content
    private boolean isEmpty(TextField editText) {
        return editText.getText().trim().length() > 0;
    }

    // Save Data into database
    private void insertData(Details details) {
        Configuration.Builder configurationBuilder = new Configuration.Builder(this);
        configurationBuilder.setPackageName("com.activeharmony.sample");
        configurationBuilder.addModelClasses(Details.class);
        double id = details.save();
        LogUtil.info("insertData", "id_value : " + id);
        restart();
    }

    // Read all Data
    private List<Details> getAll() {
        return new Select().from(Details.class).orderBy("id ASC").execute();
    }

    // Read Particular Data with id
    private Details getOne(String id) {
        return new Select().from(Details.class).where("_id = ?", id).executeSingle();
    }

    // Delete All data from table
    private void deleteAll() {
        new Delete().from(Details.class).execute();
        ToastDialog loginToast = new ToastDialog(getApplicationContext());
        loginToast.setText("Detele All successful").show();
    }

    // Delete Particular Data with id
    private void deleteOne(long id) {
        Details.delete(Details.class, id);
        ToastDialog loginToast = new ToastDialog(getApplicationContext());
        loginToast.setText("Detele id = " + id + " successful").show();
    }

    // Update Data
    private void updateData(Details details) {
        Configuration.Builder configurationBuilder = new Configuration.Builder(this);
        configurationBuilder.setPackageName("com.activeharmony.sample");
        configurationBuilder.addModelClasses(Details.class);
        double id = details.save();
        LogUtil.info("updateData", "updated_id_value : " + id);
        restart();
    }

    private void populate(List<Details> list) {
        ArrayList<String> al = new ArrayList<>();
        for (int index = 0; index < list.size(); index++) {
            al.add(list.get(index).getId() + "--" + list.get(index).getName() + "--" + list.get(index).getAge());
        }
        LogUtil.info("populate", "table content : " + al);
        ToastDialog loginToast = new ToastDialog(getApplicationContext());
        loginToast.setText(al.toString()).show();
    }

    private void populate(Details entry) {
        ToastDialog loginToast = new ToastDialog(getApplicationContext());
        if (entry != null) {
            String al = entry.getId() + "--" + entry.getName() + "--" + entry.getAge();
            LogUtil.info("populate", "table content : " + al);
            loginToast.setText(al).show();
        } else {
            loginToast.setText("Invalid Id").show();
        }
    }
}
